use rustful::{Server, Context, Response, DefaultRouter};
use std::error::Error;
use std::sync::RwLock;

use mysql;
use mysql::{Pool, Value};
use self::handlers::*;
use super::conf;

mod handlers;

fn routers() -> DefaultRouter<fn(Context, Response)>{
    let mut router = DefaultRouter::<fn(Context, Response)>::new();

    //Enables CORS
    router.find_hyperlinks = true;
    router.build().then().many(|node| {
        node.on_get(empty_method);
        node.on_options(empty_method);
    });
    router.build().path("/").then().many(|node| {
        node.on_get(service_version);
    });
    router.build().path("/login").then().many(|node| {
        node.on_get(user_login);
    });
    router.build().path("/user/:id").then().many(|node| {
        node.on_get(user_info);
    });
    router
}

pub fn run() {
    let pool = Pool::new_manual(1, 2, conf::mysql_conf()).unwrap();

    info!("Http server running...");
    let server_result = Server {
        handlers: routers(),
        host: 8030.into(),
        threads: Some(2),
        global: Box::<Pool>::new(pool).into(),
        content_type: content_type!(Application/Json; Charset = Utf8),
        ..Server::default()
    }.run();

    match server_result {
        Ok(_server) => {},
        Err(e) => error!("could not start server: {}", e.description())
    }
}

pub fn user_info(context: Context, response: Response){
    match context.variables.get("id") {
        Some(id) => {
            let global: Option<&Pool> = context.global.get();
            match global {
                Some(pool) => {
                    let query = "select user_id, user_name from game_user where user_id=:id";
                    let uid = id.as_bytes().to_vec();
                    pool.prep_exec(query, params!("id" => Value::Bytes(uid)))
                        .map(|result| {
                            result.map(|x| x.unwrap())
                                .map(|row| {
                                    let (id, name): (String, String) = mysql::from_row(row);
                                    let message = json!({"code": 0, "user": {"id": id, "name": name}});
                                    info!("{:?}", message.to_string());
                                })
                        });
                },
                None => {
                    let message = json!({"code": 0, "user": id});
                    response.send(message.to_string());
                }
            }
        },
        None => {
            let message = json!({"code": 601, "message": "参数错误！请指定用户id！"});
            response.send(message.to_string());
        }
    };
}